<?php

class UploadFile
{
    private $file = array();
    private $return = array();
    public function __construct($file)
    {
        $this->file = $file;
    }
    public function checkUpload()
    {
        if (empty($this->file)) {
            $this->return['result'] = 0;
            $this->return['message'] = '无法获取到上传文件的内容信息';
        } else {
            if ($this->file['error']) {
                switch ($this->file['error']) {
                case UPLOAD_ERR_INI_SIZE:
                case UPLOAD_ERR_FORM_SIZE:
                  $this->return['result'] = 0;
                  $this->return['message'] = '上传文件超出最大范围';
                  // no break
                case UPLOAD_ERR_PARTIAL:
                  $this->return['result'] = 0;
                  $this->return['message'] = '上传文件不完整';
                  // no break
                case UPLOAD_ERR_NO_FILE:
                  $this->return['result'] = 0;
                  $this->return['message'] = '上传文件不能为空';
                  break;
              }
            } else {
                if (is_uploaded_file($this->file['tmp_name'])) {
                    $this->return['result'] = 0;
                    $this->return['message'] = '请使用POST来进行上传';
                }
                $ext = pathinfo($this->file['name'], PATHINFO_EXTENSION);
                if (in_array($ext, array('jpg','gif','png','jpeg'))) {
                    $uploadDir = date('Y/md', $_SERVER['REQUEST_TIME']);
                    $uploadPath = './upload/'.$uploadDir;
                    $uploadName = uniqid().mt_rand(1000, 9999).'.'.$ext;
                    if (!is_dir($uploadPath)) {
                        mkdir($uploadPath, 0755, true);
                    }
                    $uploadFile = $uploadPath.'/'.$uploadName;
                    $this->return['result'] = move_uploaded_file($this->file['tmp_name'], $uploadFile);
                    $this->return['message'] = $this->return['result'] ? '上传成功': '上传失败';
                    $this->return['uploadPath'] = $this->return['result'] ? $uploadFile : '';
                } else {
                    $this->return['result'] = 0;
                    $this->return['message'] = '请上传图片文件';
                }
            }
            return $this->return;
        }
    }
}
